//
//  MainContentView.m
//  PingTu
//
//  Created by Yangfan on 15/2/5.
//  Copyright (c) 2015年 4gread. All rights reserved.
//

#import "MainContentView.h"
#import <GPUImage/GPUImage.h>

@implementation MainContentView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self DataLoad];
        [self UI];
    }
    return self;
}

- (void)DataLoad {
    _isStarDrag = NO;
}

- (void)UI {
}

- (void)setAssetsIntoPintuView:(NSArray *)assets {
    _assets = assets;
    [self updateUI:0];
}

- (void)updateUI:(int)whichMuBan {
    _whichMuBan = whichMuBan;
    for (UIView *view in [self subviews]) {
        [view removeFromSuperview];
    }
    // 底部的图片
    NSString *jpgStr = [NSString stringWithFormat:@"%dpicForStyle%dk.jpg", [self returnIntFromNSUInteger:_assets.count], whichMuBan];
    NSString *plistStr = [NSString stringWithFormat:@"%dPicForStyle%d.plist", [self returnIntFromNSUInteger:_assets.count], whichMuBan];
    UIImage *image = [UIImage imageNamed:jpgStr];
    [self setFrame:[self returnMainContentViewRect:image]];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [imageView setFrame:self.bounds];
    [self addSubview:imageView];
    
    //开始画图
    NSDictionary *styleDict = [NSDictionary dictionaryWithContentsOfFile:
                               [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:plistStr]];
    if (styleDict) {
        CGSize superSize = CGSizeFromString([[styleDict objectForKey:@"SuperViewInfo"] objectForKey:@"size"]);
        NSArray *subViewArray = [styleDict objectForKey:@"SubViewArray"];
        for(int j = 0; j < [subViewArray count]; j++) {
            CGRect rect = CGRectZero;
            UIBezierPath *path = nil;
//            ALAsset *asset = [self.assets objectAtIndex:j];
//            UIImage *image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            
            NSDictionary *subDict = [subViewArray objectAtIndex:j];
           // 开始画图了
            rect = [self rectWithArray:[subDict objectForKey:@"pointArray"] andSuperSize:superSize];// 已经得到适合当前self的画图框的rect值
            path = [UIBezierPath bezierPath];
            //生成点的坐标
            for(int i = 0; i < [[subDict objectForKey:@"pointArray"] count]; i++) {
                NSString *pointString = [[subDict objectForKey:@"pointArray"] objectAtIndex:i];
                if (pointString) {
                    CGPoint point = CGPointFromString(pointString);
                    point.x = (point.x)*self.frame.size.width/superSize.width -rect.origin.x;
                    point.y = (point.y)*self.frame.size.height/superSize.height -rect.origin.y;
                    if (i == 0) {
                        [path moveToPoint:point];
                    }else{
                        [path addLineToPoint:point];
                    }
                }
            }
            [path closePath];
            //回调或者说是通知主线程刷新，
            [self addSubview:[self createOrUpdateImageView:rect andTag:j + 1 andPath:path andAsset:[self.assets objectAtIndex:j] orImage:nil]];
        }
        
        if ([styleDict objectForKey:@"word"]) {
            UIImageView *wordImage = [[UIImageView alloc] init];
            wordImage.tag = 1111;
            CGRect rect = CGRectFromString([[styleDict objectForKey:@"word"] objectForKey:@"rect"]);
            float scale = self.frame.size.width / image.size.width;
            rect.origin.x = rect.origin.x * scale;
            rect.origin.y = rect.origin.y * scale;
            rect.size.width = rect.size.width * scale;
            rect.size.height = rect.size.height * scale;
            [wordImage setFrame:rect];
            [wordImage setImage:[UIImage imageNamed:[[styleDict objectForKey:@"word"] objectForKey:@"imgName"]]];
            [self addSubview:wordImage];
        }
    }
}

// 将画图放到一个滚动视图中，每一个图片所在的不规则或者规则区域都是一个滚动视图区域
- (OneImageFromTheLibraryInTheMuBan *)createOrUpdateImageView:(CGRect)rect andTag:(int)tag andPath:(UIBezierPath*)path andAsset:(ALAsset *)asset orImage:(UIImage *)image {
    OneImageFromTheLibraryInTheMuBan *imageView = [[OneImageFromTheLibraryInTheMuBan alloc] initWithFrame:rect];
    [imageView setClipsToBounds:YES];
    imageView.tag = tag;
    imageView.realCellArea = path;
    if (asset != nil) {
        [imageView setImageViewData:[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage]];
    } else {
        [imageView setImageViewData:image];
    }
    
    if (_assets.count == 1) {
        return imageView;
    }
    // 为图片添加拖动的手势（为了拖动改变图片位置）
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    panRecognizer.delegate = self;
    [imageView addGestureRecognizer:panRecognizer];
    
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGr.minimumPressDuration = 0.23;
    [imageView addGestureRecognizer:longPressGr];

    return imageView;
}

// 长按手势
- (void)longPressToDo:(UILongPressGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        _isStarDrag = NO;
        
        NSString *plistStr = [NSString stringWithFormat:@"%dPicForStyle%d.plist", [[NSString stringWithFormat:@"%lu", (unsigned long)_assets.count] intValue], _whichMuBan];
        NSDictionary *styleDict = [NSDictionary dictionaryWithContentsOfFile:
                                    [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:plistStr]];
         NSArray *subViewArray = [styleDict objectForKey:@"SubViewArray"];
         CGRect rect;
         CGPoint point;
         int num = 0;
         for (int i = 1; i <= subViewArray.count; i++) {
             if (i == recognizer.self.view.tag) {
                 continue;
             }
             rect = [self viewWithTag:i].frame;
             point.x = recognizer.self.view.frame.origin.x + recognizer.self.view.frame.size.width / 2.0;
             point.y = recognizer.self.view.frame.origin.y + recognizer.self.view.frame.size.height / 2.0;
             num++;
             if ([self returnRectIsContainCGPoint:rect andPoint:point]) {
                 OneImageFromTheLibraryInTheMuBan *otherImage = (OneImageFromTheLibraryInTheMuBan *)[self viewWithTag:i];
                 [self addSubview:[self createOrUpdateImageView:otherImage.frame andTag:[self returnIntFromNSUInteger:recognizer.self.view.tag] andPath:otherImage.realCellArea andAsset:nil orImage:_currentImageMuBan.imageview.image]];
                 [self addSubview:[self createOrUpdateImageView:_currentImageMuBan.frame andTag:i andPath:_currentImageMuBan.realCellArea andAsset:nil orImage:otherImage.imageview.image]];
                 
                 //               recognizer.self.view.frame = otherImage;
                 //               [self viewWithTag:i].frame = _currentImageRect;
                 
                 [(OneImageFromTheLibraryInTheMuBan *)[self viewWithTag:i] removeFromSuperview];
                 [recognizer.self.view removeFromSuperview];
                 break;
             } else {
                 if (num == subViewArray.count - 1) {
                     recognizer.self.view.frame = _currentImageMuBan.frame;
                     [[(OneImageFromTheLibraryInTheMuBan *)recognizer.self.view imageview] setImage:[[_currentImageMuBan imageview] image]];
                     for (CAShapeLayer *layer in [recognizer.self.view.layer sublayers]) {
                         if ([layer class] == [CAShapeLayer class]) {
                             layer.lineWidth = 0.0;  // 红色的边框宽度
                         }
                     }
                 }
                 continue;
             }
         }
        
        [self bringSubviewToFront:[self viewWithTag:1111]];
    } else if(recognizer.state == UIGestureRecognizerStateBegan) {
        _isStarDrag = YES;
        
        @synchronized(self){
            // 复制当前对象
            OneImageFromTheLibraryInTheMuBan *test = (OneImageFromTheLibraryInTheMuBan *)recognizer.self.view;
            _currentImageMuBan = [self createOrUpdateImageView:test.frame andTag:[self returnIntFromNSUInteger:test.tag] andPath:test.realCellArea andAsset:nil orImage:test.imageview.image];

            OneImageFromTheLibraryInTheMuBan *imageView = (OneImageFromTheLibraryInTheMuBan *)recognizer.self.view;
            for (CAShapeLayer *layer in [imageView.layer sublayers]) {
                if ([layer class] == [CAShapeLayer class]) {
                    layer.lineWidth = 1.0;  // 红色的边框宽度
                }
            }
            imageView.imageview.image = [self returnOpacityImage:[[_currentImageMuBan imageview] image] andAlpha:0.75];
            [self bringSubviewToFront:imageView];
        }
    }
}

// 拖动手势
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    if (!_isStarDrag) {
        return;
    }
    CGPoint translatedPoint = [recognizer translationInView:self];
    CGFloat x = recognizer.view.center.x + translatedPoint.x;
    CGFloat y = recognizer.view.center.y + translatedPoint.y;
    recognizer.view.center = CGPointMake(x, y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

// 返回当前拖动的图片是否已经进入另一个图片的范围内
- (BOOL)returnRectIsContainCGPoint:(CGRect)rect andPoint:(CGPoint)point {
    return CGRectContainsPoint(rect, point);
}

// 根据文件中的点的坐标，开始计算相应的点的实际坐标（因为不同设备的宽带和高度都不相同）
- (CGRect)rectWithArray:(NSArray *)array andSuperSize:(CGSize)superSize {
    CGRect rect = CGRectZero;
    CGFloat minX = INT_MAX;
    CGFloat maxX = 0;
    CGFloat minY = INT_MAX;
    CGFloat maxY = 0;
    for (int i = 0; i < [array count]; i++) {
        NSString *pointString = [array objectAtIndex:i];
        CGPoint point = CGPointFromString(pointString);
        if (point.x <= minX) {
            minX = point.x;
        }
        if (point.x >= maxX) {
            maxX = point.x;
        }
        if (point.y <= minY) {
            minY = point.y;
        }
        if (point.y >= maxY) {
            maxY = point.y;
        }
        rect = CGRectMake(minX, minY, maxX - minX, maxY - minY);
    }// 已经获取到文件中的四点坐标
    float widthScale = self.frame.size.width/superSize.width;
    float heightScale = self.frame.size.height/superSize.height;
    rect.origin.x = rect.origin.x * widthScale;
    rect.origin.y = rect.origin.y * heightScale;
    rect.size.width = rect.size.width * widthScale;
    rect.size.height = rect.size.height * heightScale;
    return rect;// 获取到适合当前self的大小的rect值
}

// 获取当前主View的Rect值
- (CGRect)returnMainContentViewRect:(UIImage *)image {
    CGRect rect;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    /**
     *  判断当前模板是0横版 1竖版 2正方形
     */
    int direction;
    if (imageWidth + 2 < imageHeight) {
        direction = 1;
    } else if (imageWidth > imageHeight + 2) {
        direction = 0;
    } else {
        direction = 2;
    }
    
    switch (direction) {
        case 0: {// 横版
            imageWidth = [[UIScreen mainScreen] bounds].size.width - 10;
            imageHeight = imageWidth * imageHeight / image.size.width;
            rect = CGRectMake(5, ([[UIScreen mainScreen] bounds].size.height - 39 - 94 - 44 - imageHeight) / 2.0, imageWidth, imageHeight);
        }
            break;
        case 1: {// 竖版
            if (ISIPHONE4) {
                imageHeight = [[UIScreen mainScreen] bounds].size.height - 44 - 39 - 93;
                imageWidth = image.size.width * imageHeight / image.size.height;
                rect = CGRectMake(([[UIScreen mainScreen] bounds].size.width - imageWidth) / 2.0, 0, imageWidth, imageHeight);
            } else {
                imageWidth = [[UIScreen mainScreen] bounds].size.width - 60;
                imageHeight = imageWidth * imageHeight / image.size.width;
                rect = CGRectMake(30, 0, imageWidth, imageHeight);
            }
        }
            break;
        case 2: {// 正方形
            imageWidth = [[UIScreen mainScreen] bounds].size.width - 10;
            rect = CGRectMake(5, ([[UIScreen mainScreen] bounds].size.height - 39 - 94 - 44 - imageWidth) / 2.0, imageWidth, imageWidth);
        }
            break;
            
        default:
            break;
    }
    
    return rect;
}

// 拿到图片的透明效果图
- (UIImage *)returnOpacityImage:(UIImage *)image andAlpha:(float)alpha {
    GPUImageOpacityFilter *gaussianBlurFilter = [[GPUImageOpacityFilter alloc] init];
    gaussianBlurFilter.opacity = alpha;
    return [gaussianBlurFilter imageByFilteringImage:image];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
